import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { NzMessageService } from 'ng-zorro-antd';
import { GroupService } from "../../group/group.service";
import { Observable } from "rxjs/Observable";
import { AliyunOssOutputUrl } from "../../../../config/api";
import { DisplayService } from "../display.service";
import { ActivatedRoute, Route, Router } from "@angular/router";
import { isInteger } from "@ng-bootstrap/ng-bootstrap/util/util";
import { LocalStorageService } from "../../../lib/service/local-storage.service";
import { AdOssUploadService } from "../../../lib/service/ad-oss-upload.service";



@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
  providers: [NzMessageService, GroupService]
})
export class AddComponent implements OnInit {

  validateForm: FormGroup;
  fileList = [];
  picList = [];
  options = [];
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  f1 = ['showcaseDetail'];
  types = 0;
  stage = 2;
  status1 = 1;
  picSizeInfo;
  _isSpinning = true;

  submitStatus = false;
  booth_number;

  //右侧预览区块
  previewTitle;
  previewsubTitle;
  previewSrc;


  /* 商品弹窗 */
  goodsModalVisible = false;
  goodsList = [];
  groupList = [];
  selectedGroup;
  keyword;
  currentClickGoods = {};
  checkedGoodsInfo = {};
  page = 1;
  pageSize = 5;
  total;
  status = '上架';
  loading = false;
  currentGoodsPrice = 0;
  comparePriceStatus = false;
  skuStatus = false;
  highPriceSkuId = null;
  ghostData = null;
  randomStatus = false;
  activity_goods_prize;




  //活动弹窗
  activityModalVisible = false;
  activityList = [];
  activityLoading = false;
  activitiesTotal;
  currentClickActivity = {};
  checkedActivityInfo = {};
  activityClickIndex;
  self = this;


  //卡券弹窗
  couponModalVisible = false;
  couponList = [];
  couponLoading = false;
  couponsTotal;
  currentClickCoupon = {};
  checkedCouponInfo = {};
  couponKeyWord = '';
  couponClickIndex;
  showcase_id;
  id;
  selectedOption;
  typesArr = {
    product: this.getGoodsList.bind(this.self),
    coupons: this.getCouponList.bind(this.self),
    activity: this.getActivityList.bind(this.self),
    picture: this.getActivityList.bind(this.self)
  };
  typeText = {
    1: { text: '普通拼团', color: 'rgb(299,112,23)' },
    2: { text: '拉新拼团', color: 'rgb(299,112,23)' },
    3: { text: '抽奖拼团', color: 'rgb(299,112,23)' },
    4: { text: '团长免单', color: 'rgb(299,112,23)' },
  };

  clearOtherList = {
    product: ['currentClickGoods', 'checkedGoodsInfo'],
    coupons: ['currentClickCoupon', 'checkedCouponInfo'],
    activity: ['currentClickActivity', 'checkedActivityInfo'],
    picture: ['currentClickActivity', 'checkedActivityInfo']
  };

  urlReg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;

  loadingWrap;
  template_id;



  constructor(
    private fb: FormBuilder,
    private _message: NzMessageService,
    private groupService: GroupService,
    public displayService: DisplayService,
    private routeInfo: ActivatedRoute,
    private router: Router,
    private localStorageService: LocalStorageService,
    private adOssUploadService: AdOssUploadService,
  ) {
    this.validateForm = this.fb.group({
      'name': ['', [Validators.required]],
      'showcase_id': ['', [Validators.required]],
      'type': ['', Validators.required],
      'sort': ['', [Validators.required,Validators.min(0),Validators.max(99)], this.integerValidators],
      'url': [''],
      'relationID': [''],
    })
  }


  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  // 整数验证
  integerValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (!isInteger(control.value)) {
        observer.next({ error: true, notInteger: true });
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  };


  ngOnInit() {
    // this.template_id = this.localStorageService.getNowApplet()['template_id'];
    // this.routeInfo.params.subscribe((params) => {
    //   if (this.validateForm.controls['showcase_id'].value != params.showcaseId) {
    //     this._isSpinning = true;
    //     this.validateForm.reset();
    //     this.picError = false;
    //     this.loadingWrap = true;
    //     this.showcase_id = params.showcaseId;
    //     this.booth_number = params.boothNumber;
    //     this.page = 1;
    //     this.pageSize = 5;
    //     this.currentClickCoupon = {};
    //     this.currentClickActivity = {};
    //     this.currentClickGoods = {};
    //     this.checkedCouponInfo = {};
    //     this.checkedActivityInfo = {};
    //     this.checkedGoodsInfo = {};
    //     this.couponModalVisible = false;
    //     this.activityModalVisible = false;
    //     this.goodsModalVisible = false;
    //     this.activityList = [];
    //     this.goodsList = [];
    //     this.couponList = [];
    //     this.fileList = [];
    //     this.picList = [];
    //     this.validateForm.controls['name'].setValue('');
    //     this.validateForm.controls['relationID'].setValue('');
    //     this.validateForm.controls['showcase_id'].setValue('');
    //     this.validateForm.controls['type'].setValue('');
    //     this.validateForm.controls['sort'].setValue('');
    //     this.validateForm.controls['url'].setValue('');
    //     this.displayService.initInfo(this, this.booth_number);
    //
    //     this.selectedOption = this.options[0];
    //     this.validateForm.controls['type'].setValue(this.selectedOption.value);
    //     this.validateForm.controls['showcase_id'].setValue(parseInt(params.showcaseId));
    //     setTimeout(() => {
    //       this._isSpinning = false;
    //     },100);
    //
    //
    //
    //
    //     if (this.displayService.list.length == 0) {
    //       this.getShowCaseList().then(() => {
    //         this.displayService.list.map((e, i) => {
    //           if (e['booth_number'] === this.booth_number) {
    //             this.displayService.showCaseIndex = i;
    //             this.displayService.name = e['name'];
    //           }
    //         });
    //       });
    //     }
    //   }
    // });
  }

  getShowCaseList() {
    return new Promise((resolve, reject) => {
      this.displayService.getShowCaseList(this.template_id).subscribe(res => {
        if (res.code === 2000) {
          this.displayService.list = res.data.data;
          let len = this.displayService.list.length;
          this.displayService.list.map((e, i) => {
            e['typeOpen'] = false;
            e['addShow'] = false;
            e['typeValue'] = '';
            this.displayService.getShowCaseDetailList(e['id']).subscribe(res1 => {
              if (res.code === 2000) {
                len--;
                let detailList = this.displayService.list[i]['detailList'] = res1.data.data;
                detailList.map((e, i) => {
                  e['edit'] = false;
                });
                if (len === 0) {
                  resolve();
                }
              };
            });
          });
        }
      })
    })
  }



  picError = false;//图片是否错误
  fileChange() {
    if (this.fileList.length === 0 && this.picList.length === 0) {
      this.picError = true;
    } else {
      this.picError = false;
    }
  }

  priceValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value > this.currentGoodsPrice) {
        observer.next({ error: true, priceToHigh: true });
      } else {
        observer.next(null);
      }
      observer.complete();
    })
  };

  //url验证
  urlValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value != '' && !this.urlReg.test(control.value)) {
        observer.next({ error: true, urlError: true });
      } else {
        observer.next(null);
      }
      observer.complete();
    })
  };

  //根据type去获取请求对应的列表
  switchTypeList(type) {
    return this.typesArr[type];
  }

  //切换选择类型
  checkType(e) {
    if (!e) {
      let controlValue = this.validateForm.controls['type'].value;
      let selectedValue = this.selectedOption.value;
      if (controlValue !== selectedValue) {
        this.validateForm.controls['type'].setValue(this.selectedOption.value);
        this.validateForm.controls['relationID'].setValue('');
        for (let k in this.clearOtherList) {
          if (k !== selectedValue) {
            this.clearOtherList[k].map((e, i) => {
              this[e] = {};
            })
          }
        }
      }
      if(selectedValue != 'page') {
        this.validateForm.controls['url'].setValue('');
      }
    }
  }



  /* 商品弹窗逻辑 */
  // 获取商品列表
  getGoodsList() {
    this.loading = true;
    this.getGroupList();
    this.groupService.getGoodsList(this.page, this.pageSize, this.selectedGroup, this.keyword, this.status).subscribe(res => {
      if (res.code === 2000) {
        this.total = res.data.total;
        const goodsList = res.data.data;
        const goodsId = [];
        goodsList.forEach(item => {
          goodsId.push(item.id);
        });
        this.groupService.getbindListAll('[' + goodsId.join(',') + ']').subscribe(rs => {
          if (rs.code === 2000) {
            const goodsjson = {};
            rs.data.forEach(item => {
              if (!goodsjson[item.goods_id]) {
                goodsjson[item.goods_id] = [item.name];
              } else {
                goodsjson[item.goods_id].push(item.name);
              }
            });
            goodsList.forEach(item => {
              if (item.goods_number) {
                item.goods_number = item.goods_number.split('|');
              }
              item.goods_category = goodsjson[item.id];
            });
          }
          this.goodsList = goodsList;
          this.loading = false;
        });
      } else {
        this._message.create('error', res.message);
      }
      this.loading = false;
    });
  }
  // 搜索商品
  searchGoods() {
    this.page = 1;
    this.getGoodsList();
  }

  //重置
  resetGoods() {
    this.keyword = '';
    this.page = 1;
    this.pageSize = 5;
    this.getGoodsList();
  }
  // 添加商品
  addGoods() {
    this.keyword = '';
    this.page = 1;
    this.currentClickGoods = JSON.parse(JSON.stringify(this.currentClickGoods));
    this.goodsModalVisible = true;
    this.getGoodsList();
  }
  // 关闭添加商品弹窗
  closeModal() {
    this.currentClickGoods = JSON.parse(JSON.stringify(this.checkedGoodsInfo));
    this.goodsModalVisible = false;
  }
  // 确认选择商品
  confirmCheckedGoods() {
    if (!Object.keys(this.currentClickGoods).length) {
      this._message.create('error', '请选择商品');
      return;
    }
    this.checkedGoodsInfo = JSON.parse(JSON.stringify(this.currentClickGoods));
    this.validateForm.controls['relationID'].setValue(this.checkedGoodsInfo['id'] + '');
    // 获取选择商品的sku
    this.groupService.getGoodsSkuList(this.currentClickGoods['id'], 100).subscribe(res => {
      if (res.code === 2000) {
        const sku = res.data.data;
        const activity_goods_prize = [];
        sku.map((val, idx) => {
          val.checked = true;
          const sku_item = { 'sku_id': val.id, 'number': val.in_stock };
          activity_goods_prize.push(sku_item);
        });
        this.activity_goods_prize = activity_goods_prize;
        this.checkedGoodsInfo['sku'] = sku;
        this.goodsModalVisible = false;
      } else {
        this._message.create('error', res.message);
      }
    });
  }

  // 获取店铺商品类型列表
  getGroupList() {
    this.groupService.getGroupList().subscribe(res => {
      this.groupList = res.data.data;
    });
  }

  _resetForm() {
    // this.validateForm.controls
    // this.validateForm.reset();
    // 'name': ['', [Validators.required]],
    //   'showcase_id': ['', [Validators.required]],
    //   'type': ['picture', Validators.required],
    //   'sort': ['', [Validators.required], this.integerValidators],
    //   'url': ['', [], this.urlValidators],
    //   'relationID': [''],
    this.picList = [];
    this.fileList = [];
    this.validateForm.controls['name'].setValue('');
    this.validateForm.controls['showcase_id'].setValue('');
    this.validateForm.controls['type'].setValue(this.options[0].value);
    this.validateForm.controls['sort'].setValue('');
    this.validateForm.controls['url'].setValue('');
    for (let k in this.clearOtherList) {
        this.clearOtherList[k].map((e, i) => {
          this[e] = {};
      })
    }
    this.validateForm.controls['relationID'].setValue('');
    // this.validateForm.controls['type'].setValue(this.options[0].value);
    console.log(this.validateForm.value);
  }

  reset() {
    this.keyword = '';
    this.page = 1;
    this.switchTypeList(this.selectedOption.value)();
  }

  /*活动弹窗逻辑*/
  // 获取活动列表
  getActivityList() {
    this.activityLoading = true;
    this.displayService.getActivityList(this.page, this.pageSize, this.keyword, this.types, this.stage , this.status1).subscribe(res => {
      if (res.code === 2000) {
        this.activityList = res.data.data;
        this.activityList.map((e, i) => {
          e['flexable'] = false;
        })
        this.activitiesTotal = res.data.total;
        this.activityLoading = false;
      }
    })
  }
  //搜索活动
  searchActivity() {
    this.page = 1;
    this.pageSize = 5;
    this.getActivityList();
  }
  //打开活动模态框
  addActivity() {
    this.keyword = '';
    this.page = 1;
    this.pageSize = 5;
    this.currentClickActivity = this.checkedActivityInfo;
    this.activityModalVisible = true;
    this.switchTypeList(this.selectedOption.value)();
  }
  //关闭活动模态框
  closeActivityModal() {
    this.activityModalVisible = false;
    this.activityList.map((e, i) => {
      e['flexable'] = false;
    });
  }
  //确认活动模态框
  confirmCheckedActivity() {
    this.checkedActivityInfo = this.currentClickActivity;
    this.checkedActivityInfo['flexable'] = false;
    this.checkedActivityInfo['type'] = this.typeText[this.currentClickActivity['activity_goods'][0]['type']];
    this.validateForm.controls['relationID'].setValue(this.checkedActivityInfo['id'] + '');
    this.activityList.map((e, i) => {
      e['flexable'] = false;
    });
    this.activityModalVisible = false;
  }
  //获取活动商品列表
  getActivityGoodsList(activityId, activityGoodsId) {
    this.displayService.getActivityGoodsList(activityId, activityGoodsId).subscribe(res => {
      if (res.code === 2000) {
        this.activityList[this.activityClickIndex]['goodsDetail'] = res.data;
      }
    })
  }

  //查看活动商品
  toggleFlexable(i) {
    this.activityClickIndex = i;
    let target = this.activityList[i];
    target['flexable'] = !target['flexable'];
    if (target['flexable']) {
      let activityId = target['id'], activity_goods_id = target['activity_goods'][0]['id'];
      this.getActivityGoodsList(activityId, activity_goods_id);
    }
  }
  //切换checked查看商品
  toggleViewActivityGoods() {
    this.checkedActivityInfo['flexable'] = !this.checkedActivityInfo['flexable'];
  }


  /*卡券弹窗逻辑*/
  addCoupon() {
    this.keyword = '';
    this.page = 1;
    this.pageSize = 5;
    this.couponModalVisible = true;
    this.switchTypeList(this.selectedOption.value)();
  }
  //获取卡券列表
  getCouponList() {
    this.couponLoading = true;
    this.displayService.getCouponList(this.page, this.pageSize, this.keyword).subscribe(res => {
      if (res.code === 2000) {
        this.couponList = res.data.data;
        this.couponsTotal = res.data.total;
        this.couponLoading = false;
      }
    });
  }
  //搜索卡券
  searchCoupon() {
    this.page = 1;
    this.getCouponList();
  }
  //关闭卡券模态框
  closeCouponModal() {
    this.couponModalVisible = false;
    this.currentClickCoupon = this.checkedCouponInfo;
  }
  //确认卡券模态框信息
  confirmCheckedCoupon() {
    this.checkedCouponInfo = this.currentClickCoupon;
    this.validateForm.controls['relationID'].setValue(this.checkedCouponInfo['card_coupons_uuid'] + '');
    this.couponModalVisible = false;
  }



  currentClick(data) {
    this.currentClickActivity = data;
  }


  uploadImg(showcase_detail_id) {
    this.adOssUploadService
      .getSignature('/v1/common/showcase_detail/' + showcase_detail_id + '?callback=true')
      .subscribe(
        res1 => {
          let length = this.fileList.filter(item => {
            return item && item != "pic";
          }).length;
          let successLen = 0;
          if (length == 0) {
            this.submitStatus = false;
            this._message.create("success", '添加成功');
            return false;
          }
          this.fileList.every((val, idx, array) => {
            if (val && val != "pic") {
              this.adOssUploadService.fileUpload(val, res1.data, this.f1[idx] + '.' + val.name.replace(/.+\./, '').toLowerCase(), 'image')
                .subscribe(res2 => {
                  successLen++;
                  if (successLen == length) {
                    this.submitStatus = false;
                    this._message.create("success", '添加成功');
                    this.displayService.list.forEach((e, i) => {
                      if (e['booth_number'] == this.booth_number) {
                        this.displayService.getCaseDetailList(this.showcase_id, i + '').then(() => {
                          this.displayService.id = showcase_detail_id;
                          this.displayService.list[this.displayService.showCaseIndex]['typeOpen'] = true;
                          this.router.navigate([`member/display/${this.showcase_id}/${showcase_detail_id}/${this.booth_number}`]);
                        });
                      }
                    });
                  }
                }
                );
            }
            return true;
          });

        }
      );
  }

  goBack() {
    // this.router.navigate([`member/display/${this.showcase_id}/$/${this.boothNumber}`]);
  }

  _submitForm() {

    console.log(this.validateForm.value);

    if (this.submitStatus) {
      return;
    }
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    this.fileChange();
    if (this.validateForm.valid && !this.picError) {
      this.submitStatus = true;
      this.displayService.addShowCase(this.validateForm.value).subscribe(res => {
        if (res.code === 2000) {
          this.uploadImg(res.data.id);
          console.log(res.data);
        } else {
          this.submitStatus = false;
          this._message.create('error', res.message);
        }
      })
    }
  }
}
